import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';
import api from '@/api';
import store from '@/store';
import ConversationClient from 'nexmo-client';
Vue.use(VueRouter);

const router = new VueRouter({
  mode: 'history',
  routes
});
var getKeyVal = function(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || ['', ''])[1].replace(/\+/g, '%20')) || null;
};
// 获取JWT token 且连接NEXMO后端
var getNexmoNew = function() {
  api.app.gettoken({ user: getKeyVal('user') }).then(res => {
    if (res.token) {
      localStorage.setItem('token', res.token);
      memberCall(res.token);
    }
  });
};
// 拿到token与后台交互连接
var memberCall = function(token) {
  new ConversationClient().login(token).then(app => {
    console.log('app:' + app);
    Vue.prototype.$nexmoApplication = app;
    app.on('member:call', (member, call) => {
      console.log(member, call);
      // 接电话
      if (call.direction === 'inbound') {
        // 根据UUID查询通话记录
        api.app.getRecordsId({ conid: member.conversation.id }).then(res => {
          if (res) {
            store.dispatch('setTelephone', res.to);
            store.dispatch('setCountryName', res.countryName);
            store.dispatch('setDialStatus', 'answer'); // 电话状态
            store.dispatch('toggleCallTrue');
          }
        });
      }
      Vue.prototype.$nexmoCall = call;
    });
  })
    .catch(err => {
      console.log(err);
      // 如果过期，再执行一次此方法
      if (err.message.indexOf('expired-token') > -1) {
        getNexmoNew();
      }
    });
};
// 校验APPID
Vue.prototype.$getClient = function(callBack) {
  var userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
  var msisdn = getKeyVal('msisdn') || (userInfo && userInfo.msisdn);
  if (!msisdn) {
    this.$router.push('/error');
  }
  api.app.getClient({ msisdn: msisdn }).then(res => {
    if (location.pathname.split('/')[1] !== res.appid) {
      router.push('/error');
    } else {
      callBack && callBack(res);
      sessionStorage.setItem('userInfo', JSON.stringify(res));
    }
  });
};
router.beforeEach((to, from, next) => {
  var token = localStorage.getItem('token');
  // 如果地址栏有值就是第一次进入
  if (getKeyVal('msisdn')) {
    getNexmoNew();
  } else {
    // 检查本地缓存是否有token，有就直接call
    if (token) {
      memberCall(token);
    } else {
      getNexmoNew();
    }
  }
  next();
});

export default router;
